package com.css.fxfzfxqh.modules.seismicHazardData.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.css.fxfzfxqh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzfxqh.base.attachment.repository.AttachmentInfoRepository;
import com.css.fxfzfxqh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzfxqh.base.response.RestResponse;
import com.css.fxfzfxqh.common.rest.JcsjRestManager;
import com.css.fxfzfxqh.common.rest.model.bo.ChinaGridBo;
import com.css.fxfzfxqh.common.rest.model.vo.ChinaGridVo;
import com.css.fxfzfxqh.modules.buildingKilometerGrid.utils.ExportZipUtils;
import com.css.fxfzfxqh.modules.earthquakeRiskAssessmentZoningReport.service.FxqhAssessReportTemplateService;
import com.css.fxfzfxqh.modules.seismicHazardData.constants.TableNameConstants;
import com.css.fxfzfxqh.modules.seismicHazardData.entity.HazardDataRecordEntity;
import com.css.fxfzfxqh.modules.seismicHazardData.entity.PsHazardDataEntity;
import com.css.fxfzfxqh.modules.seismicHazardData.entity.PsHazardDataValueEntity;
import com.css.fxfzfxqh.modules.seismicHazardData.param.psHazard.ListByRangeParam;
import com.css.fxfzfxqh.modules.seismicHazardData.param.psHazard.PageParam;
import com.css.fxfzfxqh.modules.seismicHazardData.param.psHazard.RecordPageParam;
import com.css.fxfzfxqh.modules.seismicHazardData.param.psHazard.RegionParam;
import com.css.fxfzfxqh.modules.seismicHazardData.repository.PsHazardRepository;
import com.css.fxfzfxqh.modules.seismicHazardData.service.PsHazardService;
import com.css.fxfzfxqh.modules.seismicHazardData.vo.GrIdVo;
import com.css.fxfzfxqh.modules.seismicHazardData.vo.HazardDataPageVo;
import com.css.fxfzfxqh.modules.seismicHazardData.vo.RecordsVo;
import com.css.fxfzfxqh.modules.util.hypergraph.service.HypergraphService;
import com.css.fxfzfxqh.util.*;
import com.css.fxfzfxqh.zcpt.sys.entity.SUser;
import com.css.fxfzfxqh.zcpt.sys.entity.SysUserRole;
import com.css.fxfzfxqh.zcpt.sys.service.SysAreaService;
import com.css.fxfzfxqh.zcpt.sys.service.impl.SysRoleCacheService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.xssf.usermodel.*;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.geotools.data.FeatureWriter;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.CRS;
import org.locationtech.jts.geom.MultiPolygon;
import org.opengis.feature.simple.SimpleFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Service
@Slf4j
public class PsHazardServiceImpl implements PsHazardService {

    @Autowired
    private PsHazardRepository psHazardRepository;

    @Autowired
    private JcsjRestManager jcsjRestManager;

    @Value("${image.localDir}")
    private String localDir;

    @Autowired
    private AttachmentInfoService attachmentInfoService;

    @Autowired
    private FxqhAssessReportTemplateService assessReportTemplateService;

    @Autowired
    private SysRoleCacheService roleCacheService;

    @Autowired
    private SysAreaService sysAreaService;

    @Autowired
    private HypergraphService hypergraphService;

    @Autowired
    private AttachmentInfoRepository attachmentInfoRepository;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResponse importExcel(MultipartFile file, Integer type, String ids, String year, String excelFileId) {
        try {
            String userId = PlatformSessionUtils.getUserId();
            HazardDataRecordEntity recordEntity = new HazardDataRecordEntity();
            recordEntity.setId(UUIDGenerator.getUUID());
            SUser user = assessReportTemplateService.getUser(userId);
            recordEntity.setCreateUserName(user.getUserName());
            recordEntity.setType(type == 0?"PGA":"烈度");
            //0 T年发生概率   1 烈度
            String userMaxRole = getUserMaxRole(userId);
            String mainTableName = TableNameConstants.getMainConstant(userMaxRole);
            String valueTableName = TableNameConstants.getValueConstant(userMaxRole);

            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> read = reader.read(3, reader.getRowCount());
            String titleName = "";
            List<Object> title = null;
            if (type == 0) {
                title = reader.readRow(1);
                titleName = "[公里网格Id, 经度, 纬度, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM, T年的发生概率/IM]";
            } else {
                title = reader.readRow(2);
                titleName = "[公里网格Id, 经度, 纬度, 0.04g, 0.09g, 0.19g, 0.38g, 0.75g]";
            }
            if (!title.toString().contains(titleName)) {
                return RestResponse.fail("导入失败，请检查表头是否改动");
            }
            if (read.size() == 0) {
                return RestResponse.fail("导入失败，表中无数据");
            }
            //读取T年发生概率
            List<Object> probabilityOfOccurrence = reader.readRow(2);

            //跳过前两个值，并且去除空字符串
            List<Object> result = probabilityOfOccurrence.stream()
                    .skip(3)
                    .filter(str -> str != null && !StrUtil.isBlankIfStr(str.toString()))
                    .collect(Collectors.toList());

            //shp文件中的格网id和空间数据
            List<PsHazardDataEntity> shpList = analysis(ids);

            //查询重复数据
            List<String> duplicateData = getDuplicateData(shpList, mainTableName);
            if (duplicateData.size() != 0) {
                String id = duplicateData.stream()
                        .map(s -> "'" + s + "'")
                        .collect(Collectors.joining(","));
                psHazardRepository.deleteValueByPhIdAndType(id, type.toString(), valueTableName);
            }

            ArrayList<PsHazardDataEntity> list = new ArrayList<>();

            for (List<Object> objects : read) {
                PsHazardDataEntity psHazardDataEntity = new PsHazardDataEntity();
                psHazardDataEntity.setId(objects.get(0).toString());
                psHazardDataEntity.setCreateUser(userId);
                psHazardDataEntity.setCreateTime(PlatformDateUtils.getCurrentDate());
                psHazardDataEntity.setDelFlag("0");
                psHazardDataEntity.setLongitude(objects.get(1).toString());
                psHazardDataEntity.setLatitude(objects.get(2).toString());

                for (int i = 0; i < result.size(); i++) {
                    PsHazardDataValueEntity psHazardDataValueEntity = new PsHazardDataValueEntity();
                    psHazardDataValueEntity.setId(UUIDGenerator.getUUID());
                    psHazardDataValueEntity.setPhId(psHazardDataEntity.getId());
                    psHazardDataValueEntity.setImValue(result.get(i).toString());
                    try {
                        if (!StrUtil.isBlankIfStr(objects.get(i + 3))) {
                            psHazardDataValueEntity.setFImValue(Double.parseDouble(objects.get(i + 3).toString()));
                        }
                    } catch (IndexOutOfBoundsException e) {
                        log.error("格网id为{}的数据异常", psHazardDataEntity.getId());
                    }
                    psHazardDataValueEntity.setType(type.toString());
                    psHazardRepository.savePsHazardDataValue(psHazardDataValueEntity, valueTableName);
                }
                list.add(psHazardDataEntity);
            }

            //将shp中的空间数据加到excel读取到的数据中   使用公里格网id对应
            Map<String, PsHazardDataEntity> psHazardMap = shpList.stream()
                    .collect(Collectors.toMap(
                            PsHazardDataEntity::getId,
                            Function.identity()));

            List<PsHazardDataEntity> collect = list.parallelStream()
                    .peek(item2 -> {
                        PsHazardDataEntity entity = psHazardMap.get(item2.getId());
                        if (entity != null) {
                            item2.setGeom(entity.getGeom());
                            item2.setProvince(entity.getProvince());
                            item2.setCity(entity.getCity());
                            item2.setCounty(entity.getCounty());
                        }
                    })
                    .collect(Collectors.toList());

            //对省市县进行去重
            List<PsHazardDataEntity> newList = collect.stream()
                    .distinct()
                    .collect(Collectors.toList());

            String region = newList.stream()
                    .map(item -> item.getProvince() + "-" + item.getCity() + "-" + item.getCounty())
                    .collect(Collectors.joining("，", "", ""));

            recordEntity.setFileIds(ids + "," + excelFileId);
            recordEntity.setRegion(region);
            recordEntity.setCreateTime(PlatformDateUtils.getCurrentDate());
            recordEntity.setCreateUser(userId);
            recordEntity.setDataRange(TableNameConstants.getRoleConstant(userMaxRole));

            collect.parallelStream().forEach(it -> {
                PsHazardDataEntity dataEntity = psHazardRepository.getPsHazardDataById(it.getId(), mainTableName);
                it.setYear(year);
                it.setFileId(ids + "," + excelFileId);
                if (PlatformObjectUtils.isNotEmpty(dataEntity)) {
                    if(!dataEntity.getType().contains(type.toString())){
                        it.setType(dataEntity.getType()+","+type);
                    }else {
                        it.setType(dataEntity.getType());
                    }
                    it.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                    it.setUpdateUser(userId);
                    psHazardRepository.update(it, mainTableName);
                } else {
                    it.setType(type.toString());
                    psHazardRepository.savePsHazardData(it, mainTableName);
                }
            });
            psHazardRepository.saveRecord(recordEntity);
            hypergraphService.getWorkspaceReload(TableNameConstants.getMainConstant(userMaxRole));
            return RestResponse.succeed("导入成功!");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询重复数据
     *
     * @param list
     * @return
     */
    private List<String> getDuplicateData(List<PsHazardDataEntity> list, String mainTableName) {
        List<String> data = psHazardRepository.getAllKilometerGridId(mainTableName);
        return data.stream()
                .filter(item -> list.stream().anyMatch(other -> other.getId().equals(item)))
                .collect(Collectors.toList());
    }

    private List<PsHazardDataEntity> analysis(String ids) {
        Map<String, Object> map = new HashMap<>();
        this.uniformFileName(ids);
        ParsingResult shpData = getShpData(ids);
        //是否成功
        if (!shpData.getMessage().equals("ok")) {
            map.put("res", false);
            map.put("mess", shpData.getMessage());
        }
        List<List<Object>> shpList = shpData.getShpList();
        List<PsHazardDataEntity> resultList = new ArrayList<>();

        for (int i = 0; i < shpList.size(); i++) {
            List<Object> list = shpList.get(i);
            PsHazardDataEntity entity = new PsHazardDataEntity();
            if (!PlatformObjectUtils.isEmpty(list.get(0))) {
                entity.setGeom(list.get(0).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(1))) {
                entity.setId(list.get(1).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(2))) {
                entity.setProvince(list.get(2).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(3))) {
                entity.setCity(list.get(3).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(4))) {
                entity.setCounty(list.get(4).toString());
            }
            resultList.add(entity);
        }
        return resultList;
    }

    /**
     * 统一文件名
     *
     * @param fileIds
     */
    public void uniformFileName(String fileIds) {
        String[] idList = fileIds.split(",");
        AttachmentInfoEntity attachRoot = attachmentInfoService.getAttach(idList[0]);
        String attachRootPath = attachRoot.getAttachPath();
        String filePathCurrTime = getFilePathCurrTime(attachRootPath);
        for (int i = 1; i < idList.length; i++) {
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(idList[i]);
            if (getFilePathCurrTime(attach.getAttachPath()).equals(filePathCurrTime)) {
                continue;
            }
            String attachPath = attach.getAttachPath();
            String fileDiskPath = localDir + attachPath;
            FileUtil.rename(new File(fileDiskPath), getNonSuffixFileName(attach.getAttachName()) + "_" + filePathCurrTime + "." + FileUtil.getSuffix(attach.getAttachName()), true);
            String[] s = attachPath.split("_");
            attach.setAttachPath(s[0] + "_" + filePathCurrTime + "." + FileUtil.getSuffix(attach.getAttachName()));
            attachmentInfoService.update(attach);
        }
    }

    private String getFilePathCurrTime(String filePath) {
        return filePath.split("_")[1].replaceAll("." + FileUtil.getSuffix(filePath.split("_")[1]), "");
    }

    private String getNonSuffixFileName(String fileName) {
        return fileName.replaceAll("." + FileUtil.getSuffix(fileName), "");
    }

    public ParsingResult getShpData(String fileIds) {
        //.prj结尾用来校验是否为2000坐标系
        String prj = "";
        //.cpg文件用来获得编码格式,例如utf-8
        String cpg = "";
        //.shp文件用来获得数据
        String shp = "";
        //根据id获取真实地址
        String[] split = fileIds.split(",");
        for (String id : split) {
            //根据id和文件名获取真实的放在磁盘上的文件
            AttachmentInfoEntity attachmentInfoEntity = attachmentInfoService.getAttach(id);
            String attachPath = attachmentInfoEntity.getAttachPath();
            String substring = attachPath.substring(attachPath.length() - 4);
            if (substring.equals(".prj")) {
                prj = localDir + File.separator + attachPath;
            } else if (substring.equals(".cpg")) {
                cpg = localDir + File.separator + attachPath;
            } else if (substring.equals(".shp")) {
                shp = localDir + File.separator + attachPath;
            }
        }
        return ShpAnalyticUtil.analytic(prj, cpg, shp);
    }

    @Override
    public void exportExcel(Integer sheetType, Integer region, List<RegionParam> regionList, String rangeValue, HttpServletResponse response) {
        String excelName = "";
        if (sheetType == 0) {
            excelName = "T年发生概率导入模板.xlsx";
        } else {
            excelName = "烈度导入模板.xlsx";
        }
        try {
            //shp
            String millis = System.currentTimeMillis() + "";
            File file = new File(localDir + File.separator + "zip");
            if (!file.exists()) file.mkdirs();
            //创建文件路径
            String name = "发生概率地震危险性数据" + millis;
            String targetPath = file + File.separator + excelName;

            File newFile = excelPath(excelName, targetPath);

            String path = file + File.separator + name + ".shp";
            File file1 = new File(path);
            //添加创建的路径
            ShapefileDataStoreFactory sf = new ShapefileDataStoreFactory();
            //创建shape文件数据仓库根据工厂
            ShapefileDataStore ds = (ShapefileDataStore) sf.createDataStore(file1.toURI().toURL());
            ds.setCharset(StandardCharsets.UTF_8);
            //创建要素模板
            SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
            tb.setCRS(CRS.decode("EPSG:4490"));
            //设置全局状态
            tb.setName("shapefile");
            //添加属性类型
            tb.add("公里格网id", String.class);
            tb.add("省", String.class);
            tb.add("市", String.class);
            tb.add("县", String.class);
            tb.add("the_geom", MultiPolygon.class);
            ds.createSchema(tb.buildFeatureType());
            InputStream is = null;
            XSSFWorkbook workbook = null;
            XSSFSheet sheet = null;
            is = Files.newInputStream(newFile.toPath());// 将excel文件转为输入流

            workbook = new XSSFWorkbook(is);// 创建workbook
            // 获取第一个sheet
            sheet = workbook.getSheetAt(0);

            ListByRangeParam param = toParam(regionList, region, rangeValue);
            ChinaGridBo geographicLocationByRange = jcsjRestManager.getGeographicLocationByRange(param);
            List<ChinaGridVo> data = geographicLocationByRange.getData();
            log.info("格网数据:{}", data.size());
            ArrayList<PsHazardDataEntity> dataList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(data)) {
                FeatureWriter featureWriter = ds.getFeatureWriter(ds.getTypeNames()[0], null);
                data.forEach(it -> {
                    try {
                        SimpleFeature feature = (SimpleFeature) featureWriter.next();
                        feature.setAttribute(1, it.getId());
                        feature.setAttribute(2, it.getProvince());
                        feature.setAttribute(3, it.getCity());
                        feature.setAttribute(4, it.getCounty());
                        feature.setAttribute("the_geom", it.getGeom());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                    PsHazardDataEntity entity = new PsHazardDataEntity();
                    entity.setKilometerGridId(it.getId());
                    entity.setLongitude(it.getXCenter());
                    entity.setLatitude(it.getYCenter());
                    dataList.add(entity);
                });

                featureWriter.write();
                featureWriter.close();
                ds.dispose();
                // 写数据
                FileOutputStream fos = new FileOutputStream(newFile);
                XSSFRow row = sheet.getRow(2);
                if (row == null) {
                    row = sheet.createRow(2);
                }
                XSSFCell cell = row.getCell(0);
                if (cell == null) {
                    cell = row.createCell(0);
                }

                for (int m = 0; m < dataList.size(); m++) {
                    PsHazardDataEntity entity = dataList.get(m);
                    row = sheet.createRow(m + 3);
                    // id
                    cell = row.createCell(0);
                    cell.setCellValue(entity.getKilometerGridId());
                    // 经度
                    cell = row.createCell(1);
                    cell.setCellValue(entity.getLongitude());
                    // 纬度
                    cell = row.createCell(2);
                    cell.setCellValue(entity.getLatitude());

                    cell = row.createCell(3);
                    cell.setCellValue(entity.getGeom());
                }
                workbook.write(fos);
                fos.flush();
                fos.close();

                File file3 = new File(file + File.separator + name + ".cpg");
                DataOutputStream dos = new DataOutputStream(new FileOutputStream(file3));
                dos.write("UTF-8".getBytes());
                dos.close();
                String zipPath = file + File.separator + name + ".zip";
                File zipFile = new File(zipPath);
                InputStream input = null;
                ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
                //zip的名称为
                zipOut.setComment(name);
                String[] shpFiles = new String[]{
                        file + File.separator + name + ".dbf",
                        file + File.separator + name + ".prj",
                        file + File.separator + name + ".shp",
                        file + File.separator + name + ".shx",
                        file + File.separator + name + ".fix",
                        file + File.separator + name + ".cpg",
                        targetPath
                };
                for (int i = 0; i < shpFiles.length; i++) {
                    File file2 = new File(shpFiles[i]);
                    input = new FileInputStream(file2);
                    zipOut.putNextEntry(new ZipEntry(file2.getName()));
                    int temp = 0;
                    while ((temp = input.read()) != -1) {
                        zipOut.write(temp);
                    }
                    input.close();
                }
                zipOut.close();
            }
            String zipName = "发生概率地震危险性数据" + millis;
            String zipPath = file + File.separator + zipName + ".zip";
            String fileName = new String((zipName + ".zip").getBytes());
            String newName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Disposition", "attchment;filename=" + newName);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Method", "POST,GET");
            //该流不可以手动关闭,手动关闭下载会出问题,下载完成后会自动关闭
            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream inputStream = new FileInputStream(zipPath);
            // copy方法为文件复制,在这里直接实现了下载效果
            IOUtils.copy(inputStream, outputStream);
            // 关闭输入流
            inputStream.close();
            //删除中间文件
            File[] files = file.listFiles();
            for (File file2 : files) {
                file2.delete();
            }
        } catch (Exception e) {
            log.error("下载模板失败:{}", e.getMessage(), e);
        }
    }

    /**
     * 创建excel
     *
     * @param excelName
     * @return
     */
    private File excelPath(String excelName, String targetPath) {
        File newFile = new File(targetPath);
        //删除上次导出带数据的模板
        if (newFile.exists()) {
            newFile.delete();
        }

        //模板路径
        String excelUrl = ClassUtils.getDefaultClassLoader()
                .getResource("").getPath() + "excel/" + excelName;
        log.info("模板路径:{}", excelUrl);

        // 从模板路径复制一份到目标路径，如果不复制会出现模板数据清空不了的情况
        FileUtil.copy(excelUrl, targetPath, false);
        return new File(targetPath);
    }

    private ListByRangeParam toParam(List<RegionParam> regionList, Integer region, String rangeValue) {
        ListByRangeParam param = new ListByRangeParam();
        if (region == 0) {
            ArrayList<ListByRangeParam.Range> rangeList = new ArrayList<>();
            regionList.forEach(it -> {
                ListByRangeParam.Range range = new ListByRangeParam.Range();
                range.setProvince(it.getProvinceName());
                range.setCity(it.getCityName());
                range.setCounty(it.getCountyName());
                rangeList.add(range);
            });
            param.setRangeList(rangeList);
        } else {
            param.setGeom(rangeValue);
        }
        return param;
    }

    @Override
    public RestResponse getByKilometerGridId(String kilometerGridId, Integer type) {
        String userMaxRole = getUserMaxRole(PlatformSessionUtils.getUserId());
        String valueTableName = TableNameConstants.getValueConstant(userMaxRole);
        List<GrIdVo> grIdList = new ArrayList<>();
//        PsHazardDataEntity psHazardData = psHazardRepository.getPsHazardDataByKilometerGridId(kilometerGridId, type, mainTableName);
        PsHazardDataEntity psHazardData = null;
        HashMap<String, Object> map = new HashMap<>();

        if (psHazardData != null) {
            List<PsHazardDataValueEntity> psHazardDataValueList = psHazardRepository.getPsHazardDataValueByPhId(psHazardData.getId(), type.toString(), valueTableName);

            for (PsHazardDataValueEntity entity : psHazardDataValueList) {
                GrIdVo grIdVo = new GrIdVo();
                grIdVo.setKilometerGridId(psHazardData.getKilometerGridId());
                grIdVo.setLongitude(psHazardData.getLongitude());
                grIdVo.setLatitude(psHazardData.getLatitude());
                grIdVo.setImValue(entity.getImValue());
                grIdVo.setFImValue(entity.getFImValue());
                grIdList.add(grIdVo);
            }

            if (type == 0) {
                grIdList = grIdList.stream()
                        .sorted(Comparator.comparing(GrIdVo::getImValue))
                        .collect(Collectors.toList());
            }

            if (PlatformObjectUtils.isNotEmpty(psHazardData.getFileId())) {
                String fileId = psHazardData.getFileId();
                map.put("fileId", attachmentInfoRepository.getAttach(fileId));
            }
        }
        map.put("data", grIdList);
        return RestResponse.succeed(map);
    }

    @Override
    public RestResponse getByRegionId() throws Exception {
        //拿到所在省id，然后查出来code
        String geom = "";
        String userId = PlatformSessionUtils.getUserId();
        String userMaxRole = getUserMaxRole(userId);
        SUser user = assessReportTemplateService.getUser(userId);

        if (userMaxRole.equals("qh_gj_role")) {
            geom = "全部";
        } else if (userMaxRole.equals("qh_province_role")) {
            if (PlatformObjectUtils.isEmpty(user.getProvinceId())) {
                return RestResponse.fail("用户所在省id为空!");
            }
            String code = sysAreaService.getDivisionCodeById(user.getProvinceId());
            geom = jcsjRestManager.getGeomByCode(code.trim().replace("\"", ""), "1");
        } else if (userMaxRole.equals("qh_city_role")) {
            if (PlatformObjectUtils.isEmpty(user.getCityId())) {
                return RestResponse.fail("用户所在市id为空!");
            }
            String code = sysAreaService.getDivisionCodeById(user.getCityId());
            geom = jcsjRestManager.getGeomByCode(code.trim().replace("\"", ""), "2");
        } else if (userMaxRole.equals("ph_county_role")) {
            if (PlatformObjectUtils.isEmpty(user.getCountyId())) {
                return RestResponse.fail("用户所在区/县id为空!");
            }
            String code = sysAreaService.getDivisionCodeById(user.getCountyId());
            geom = jcsjRestManager.getGeomByCode(code.trim().replace("\"", ""), "3");
        }
        HashMap<String, Object> map = new HashMap<>();
        if (PlatformObjectUtils.isNotEmpty(user.getProvinceId())) {
            map.put("provinceName", sysAreaService.getAreaNameByAreaId(user.getProvinceId()));
        } else {
            map.put("provinceName", "");
        }
        if (PlatformObjectUtils.isNotEmpty(user.getCityId())) {
            map.put("cityName", sysAreaService.getAreaNameByAreaId(user.getCityId()));
        } else {
            map.put("cityName", "");
        }
        if (PlatformObjectUtils.isNotEmpty(user.getCountyId())) {
            map.put("countyName", sysAreaService.getAreaNameByAreaId(user.getCountyId()));
        } else {
            map.put("countyName", "");
        }
        map.put("provinceId", user.getProvinceId());
        map.put("cityId", user.getCityId());
        map.put("countyId", user.getCountyId());
        map.put("role", userMaxRole);
        map.put("geom", geom);
        return RestResponse.succeed(map);
    }

    private String getUserMaxRole(String uploadUid) {
        List<SysUserRole> roleList = roleCacheService.getRole(uploadUid);
        if (roleList == null) {
            throw new RuntimeException("未查询到用户角色信息!");
        }
        List<String> roleCodeList = roleList.stream().map(r -> r.getRoleCode()).collect(Collectors.toList());
        if (roleCodeList.contains("qh_gj_role") || roleCodeList.contains("fxqh_test_role")) {
            return "qh_gj_role";
        }
        if (roleCodeList.contains("qh_province_role")) {
            return "qh_province_role";
        }
        if (roleCodeList.contains("qh_city_role")) {
            return "qh_city_role";
        }
        if (roleCodeList.contains("ph_county_role")) {
            return "ph_county_role";
        }
        return null;
    }

    @Override
    public Map<String, Object> page(PageParam param) {
        String userId = PlatformSessionUtils.getUserId();
        String userMaxRole = getUserMaxRole(userId);
        if (PlatformObjectUtils.isNotEmpty(userMaxRole)) {
            SUser user = assessReportTemplateService.getUser(userId);
            String mainTableName = TableNameConstants.getMainConstant(userMaxRole);
            String valueTableName = TableNameConstants.getValueConstant(userMaxRole);
            if (userMaxRole.equals("qh_province_role")) {
                if(PlatformObjectUtils.isEmpty(param.getProvince())){
                    param.setProvince(sysAreaService.getAreaNameByAreaId(user.getProvinceId()));
                }
            }
            if (userMaxRole.equals("qh_city_role")) {
                if(PlatformObjectUtils.isEmpty(param.getProvince())){
                    param.setProvince(sysAreaService.getAreaNameByAreaId(user.getProvinceId()));
                }
                if(PlatformObjectUtils.isEmpty(param.getCity())){
                    param.setCity(sysAreaService.getAreaNameByAreaId(user.getCityId()));
                }
            }
            if (userMaxRole.equals("ph_county_role")) {
                if(PlatformObjectUtils.isEmpty(param.getProvince())){
                    param.setProvince(sysAreaService.getAreaNameByAreaId(user.getProvinceId()));
                }
                if(PlatformObjectUtils.isEmpty(param.getCity())){
                    param.setCity(sysAreaService.getAreaNameByAreaId(user.getCityId()));
                }
                if(PlatformObjectUtils.isEmpty(param.getCounty())){
                    param.setCounty(sysAreaService.getAreaNameByAreaId(user.getCountyId()));
                }
            }
            Map<String, Object> page = psHazardRepository.page(param, mainTableName);
            page.forEach((k, v) -> {
                if (k.equals("rows")) {
                    ArrayList<HazardDataPageVo> list = (ArrayList<HazardDataPageVo>) v;
                    list.forEach(it -> {
                        it.setUserName(assessReportTemplateService.getUser(it.getCreateUser()).getUserName());
                        it.setTime(it.getCreateTime());
                        if(PlatformObjectUtils.isNotEmpty(it.getUpdateUser())){
                            it.setUserName(assessReportTemplateService.getUser(it.getUpdateUser()).getUserName());
                            it.setTime(it.getUpdateTime());
                        }
                        it.setDataType(param.getType());
                        List<PsHazardDataValueEntity> psHazardDataValueList = psHazardRepository.getPsHazardDataValueByPhId(it.getId(), param.getType().toString(), valueTableName);
                        List<GrIdVo> grIdList = new ArrayList<>();
                        if (psHazardDataValueList.size()!=0) {
                            for (PsHazardDataValueEntity valueEntity : psHazardDataValueList) {
                                GrIdVo grIdVo = new GrIdVo();
                                grIdVo.setKilometerGridId(it.getId());
                                grIdVo.setLongitude(it.getLongitude());
                                grIdVo.setLatitude(it.getLatitude());
                                grIdVo.setImValue(valueEntity.getImValue());
                                grIdVo.setFImValue(valueEntity.getFImValue());
                                grIdList.add(grIdVo);
                            }
                            if (param.getType() == 0) {
                                grIdList = grIdList.stream()
                                        .sorted(Comparator.comparing(GrIdVo::getImValue))
                                        .collect(Collectors.toList());
                            }
                            it.setGrIdList(grIdList);
                        }
                    });
                }
            });
            return page;
        }
        return new HashMap<>();
    }

    @Override
    public Map<String, Object> uploadRecords(RecordPageParam param) {
        String userId = PlatformSessionUtils.getUserId();
        String userMaxRole = getUserMaxRole(userId);
        String region = "";
        Integer dataRange = null;
        if (PlatformObjectUtils.isNotEmpty(userMaxRole)) {
            SUser user = assessReportTemplateService.getUser(userId);
            if (userMaxRole.equals("qh_gj_role")) {
                dataRange = 0;
            }
            if (userMaxRole.equals("qh_province_role")) {
                dataRange = 1;
                region = sysAreaService.getAreaNameByAreaId(user.getProvinceId());
            }
            if (userMaxRole.equals("qh_city_role")) {
                dataRange = 2;
                String province = sysAreaService.getAreaNameByAreaId(user.getProvinceId());
                String city = sysAreaService.getAreaNameByAreaId(user.getCityId());
                region = province + "-" + city;
            }
            if (userMaxRole.equals("ph_county_role")) {
                dataRange = 3;
                String province = sysAreaService.getAreaNameByAreaId(user.getProvinceId());
                String city = sysAreaService.getAreaNameByAreaId(user.getCityId());
                String county = sysAreaService.getAreaNameByAreaId(user.getCountyId());
                region = province + "-" + city + "-" + county;
            }
            Map<String, Object> page = psHazardRepository.uploadRecords(param, dataRange, region);
            page.forEach((k, v) -> {
                if (k.equals("rows")) {
                    ArrayList<RecordsVo> list = (ArrayList<RecordsVo>) v;
                    list.forEach(it -> {
                        List<RecordsVo.AttachmentInfo> dataFileList = new ArrayList<>();
                        String[] dataFileIds = it.getFileIds().split(",");
                        for (String dataFileId : dataFileIds) {
                            AttachmentInfoEntity attach = attachmentInfoService.getAttach(dataFileId);
                            if (null != attach) {
                                RecordsVo.AttachmentInfo info = new RecordsVo.AttachmentInfo();
                                info.setId(attach.getAttachId());
                                info.setName(attach.getAttachName());
                                dataFileList.add(info);
                            }
                        }
                        it.setList(dataFileList);
                    });
                }
            });
            return page;
        }
        return new HashMap<>();
    }

    @Override
    public void export(String ids, HttpServletResponse response) {
        ArrayList<AttachmentInfoEntity> attachList = new ArrayList<>();
        List<String> fileNameList = new ArrayList<>();
        for (String id : ids.split(",")) {
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(id);
            attachList.add(attach);
            fileNameList.add(attach.getAttachName());
        }
        String fileName = fileNameList.get(0).split("\\.")[0];
        File[] srcFiles = new File[attachList.size()];
        for (int i = 0; i < attachList.size(); i++) {
            srcFiles[i] = new File(localDir + attachList.get(i).getAttachPath());
        }
        ExportZipUtils.createZipFile(response, srcFiles, fileNameList, fileName);
    }
}
